import Uploader from '../lib/uploader'
// import Uploader from 'miniprogram-uploader' // TODO: 引入第三方组件

// TODO: 使用测试机的IP地址，在工具设置中忽略域名校验
const SERVER_URL = '10.30.54.161:8082'
const MERGE_URL = `http://${SERVER_URL}/merge`
const VERIFY_URL = `http://${SERVER_URL}/verify`
const UPLOAD_URL = `http://${SERVER_URL}/upload`

const MB = 1024 * 1024
Page({
  data: {
    progress: 0,
    uploadedSize: 0,
    averageSpeed: 0,
    timeRemaining: 0,
    testChunks: false,
    chunkSize: 1 * MB, // 分块大小，默认 5 * 1024 * 1204 B
    videoUrl: '', // 视频地址
    imageUrl: '', // 图片地址
  },

  onLoad() {},

  /**
   * 是否计算文件 MD5
   * @param {*} e
   */
  onTestChunksChange(e) {
    const value = e.detail.value
    this.setData({
      testChunks: value
    })
  },

  /**
   * 分片大小（MB）
   * @param {*} e
   */
  onChunkSizeChange(e) {
    const value = e.detail.value
    console.log('value: ', value)
    /* this.setData({
      chunkSize: value * MB || this.data.chunkSize
    }) */
  },

  /**
   * 上传文件
   */
  uploadFile(tempFilePath, size){
    console.log('isSupport: ', Uploader.isSupport());
    if (!Uploader.isSupport()) {
      wx.showToast({
        title: '分片上传在 2.10.0 版本以上支持',
        icon: 'none',
        duration: 3000
      })
      return
    }
    console.log('开始向服务器上传文件');

    const uploader = new Uploader({
      tempFilePath,
      totalSize: size,
      chunkSize: this.data.chunkSize, // 分块大小，
      // query: {}, // 上传分块时可添加自定义的参数
      fileName: 'demo', // 文件名
      uploadUrl: UPLOAD_URL, // 接收分块（Post）
      mergeUrl: MERGE_URL, // 合并分块
      // verifyUrl: VERIFY_URL, // 秒传验证
      // testChunks: this.data.testChunks, // 是否需要进行秒传验证，默认为 false
      verbose: true // 是否输出开始日志，默认 false
    })
    uploader.on('retry', (res) => {
      console.log('retry', res.url)
    })

    uploader.on('complete', (res) => {
      console.log('upload complete', res)
    })

    uploader.on('success', (res) => {
      console.log('upload success', res)
    })

    uploader.on('fail', (res) => {
      console.log('upload fail', res)
    })

    uploader.on('progress', (res) => {
      this.setData({
        progress: res.progress,
        uploadedSize: parseInt(res.uploadedSize / 1024, 0),
        averageSpeed: parseInt(res.averageSpeed / 1024, 0),
        timeRemaining: res.timeRemaining
      })
    })

    uploader.upload()

    this.uploader = uploader
  },

  /**
   * 选择视频
   */
   async chooseVideo() {
    console.log('点击了【选择视频】按钮');
    this.reset()
    const {
      tempFilePath,
      size,
    } = await wx.chooseVideo({
      sourceType: ['album'],
      compressed: false
    })
    this.setData({
      videoUrl: tempFilePath
    })

    this.uploadFile(tempFilePath, size)
  },

  /**
   * 选择图片
   */
   async chooseImage() {
    console.log('点击了【选择图片】按钮');
    this.reset()

    const {
      tempFiles
    } = await wx.chooseImage({
      sourceType: ['album']
    })
    console.log('image: ', tempFiles[0].path)
    this.setData({
      imageUrl: tempFiles[0].path
    })
    this.uploadFile(tempFiles[0].path, tempFiles[0].size)
  },

  /**
   * 重置数据
   */
  reset() {
    this.setData({
      progress: 0,
      uploadedSize: 0,
      averageSpeed: 0,
      timeRemaining: 0,
    })
  },

  /**
   * 重新上传
   */
  handleUpload() {
    console.log('点击了【重新上传】按钮');
    this.uploader && this.uploader.upload()
  },

  /**
   * 暂停上传
   */
  handlePause() {
    console.log('点击了【暂停上传】按钮');
    this.uploader && this.uploader.pause()
  },

  /**
   * 恢复上传
   */
  handleResume() {
    console.log('点击了【恢复上传】按钮');
    this.uploader && this.uploader.resume()
  },

  /**
   * 取消上传
   */
  handleCancel() {
    console.log('点击了【取消上传】按钮');
    this.uploader && this.uploader.cancel()
  }
})
